<template>
  <div class="one flex_column">
    <everyHorn />
    <div v-if="btnOne" class="tital_home">
      <img src="@/assets/img/home-page/one_title.png" alt="">
      <h2>{{ dataList[index]?dataList[index].name:'' }}</h2>
    </div>
    <div v-if="btnOne" class="main flex_1">
      <div id="progressChart" class="chart" />
      <div id="storageChart" class="charts" />
    </div>
    <div v-else class="flex_1  flex_center">
      暂无权限
    </div>
  </div>
</template>

<script>
import everyHorn from './every_horn.vue'
import { authoritymanagement } from '@/assets/js/utils.js'
const echarts = require('echarts')
var myChart // 全局定义变量
var progressChart// 全局定义变量
export default {
  name: '',
  components: {
    everyHorn
  },
  data() {
    return {
      dataList: [
        { name: '泸州仓库', use: '65', average: '0.6' },
        { name: '贵阳仓库', use: '80', average: '0.8' }
      ],
      index: 0,
      angle: 0,
      option: '',
      timerId: '',
      intervalTime: null,
      chartData: {},
      btnOne: '' // 查看权限
    }
  },
  created() {
    // this.getStorage()
  },
  mounted() {
    // 获取当前登录人权限
    let RoleCode = this.$getLocalItem('jx_RoleCode')
    this.btnOne = authoritymanagement(RoleCode, 'lypc_btn_btnOne')
    if (this.btnOne) {
      this.getStorage()
      this.intervalTime = setInterval(() => {
        console.log('one setInterval1 timer execute')
        this.index++
        if (this.index >= this.dataList.length) {
          this.index = 0
        }
        clearInterval(this.timerId)
        // this.init()
        this.getData()
      }, 60000)
    }
  },
  beforeDestroy() {
    clearInterval(this.intervalTime)
    clearInterval(this.timerId)
    myChart = null
  },
  methods: {
    async getStorage(val) {
      val = val || ''
      let res = await this.$API.deviceManagement.reqStorageListPermission({ page: 1, size: 100, name: val })
      if (res) {
        this.dataList = res.responseBody.records || []
        if (this.dataList.length > 0) {
          this.getData()
        }
      }
    },
    async getData() {
      let res = await this.$API.homePage.reqStorageNewHome(this.dataList[this.index].id)
      if (res) {
        this.chartData = res.responseBody
        this.init()
      }
    },
    init() {
      this.drawChart()
      this.drawChart2()
    },
    drawChart() {
      // 做环形图的本质是 radius: ['内半径', '外半径'] 内半径!=0
      // 画渐变色的原理是：data里面可以设置itemStyle
      // this.angle = 0 // 角度，用来做简单的动画效果的
      const self = this
      this.timerId = ''
      var value = this.chartData.velocity // 今日完成78%
      // const backgroundColor = '#101736'
      // const title = {
      //   text: '今日进度',
      //   textStyle: {
      //     color: '#fff',
      //     fontSize: 16
      //   },
      //   padding: 0,
      //   top: 35,
      //   left: 'center'
      // }
      const legend = {
        show: false
      }
      const tooltip = {
        show: false
      }
      const colors = ['#A098FC', '#4386FA', '#4FADFD', '#0CD3DB', '#646CF9']
      const innerRingColor = {
        type: 'linear',
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        colorStops: [0, 0.3, 0.6, 0.8, 1].map((offset, index) => ({ offset, color: colors[index] })),
        global: false // 缺省为 false
      }
      this.option = {
        // backgroundColor,
        color: colors,
        // title,
        tooltip,
        legend,
        grid: {
          top: '1%',
          bottom: '1%'
        },
        series: [
          {
            name: '',
            type: 'pie',
            center: ['50%', '50%'], // 圆心的位置
            radius: ['40%', '45%'], // 环形图的本质就在这里 [内半径!=0，外半径] 外半径越大，圆越大
            avoidLabelOverlap: false, // 做同心圆用到
            clockwise: false, // 顺时针排列
            startAngle: 90, // 起始角度 影响不大
            label: {
              show: true, // false不显示饼图上的标签
              position: 'center', // inside（在饼图上显示）,outside(默认就会出现引导线) center
              formatter: '库容占用比：' + this.chartData.velocity + '\n平效测算：' + this.chartData.warehousing + '\n周转率：' + this.chartData.velocity,
              fontSize: 14,
              color: '#fff',
              lineHeight: 20
            },

            data: [
              { value: value, name: '完成', itemStyle: { color: innerRingColor, opacity: 1 }},
              { value: 100 - value, name: '未完成', itemStyle: { color: '#aac9e9' }}
            ].sort((a, b) => b.value - a.value), // 数组从大到小排序

            emphasis: {
              scale: false
            }
          },
          {
            name: '',
            type: 'pie',
            center: ['50%', '50%'], // 圆心的位置
            radius: ['60%', '73%'], // 环形图的本质就在这里 [内半径!=0，外半径] 外半径越大，圆越大
            avoidLabelOverlap: false, // 做同心圆用到
            clockwise: false, // 顺时针排列
            startAngle: 90, // 起始角度 影响不大
            label: {
              show: false // false不显示饼图上的标签

            },

            data: [
              { value: value, name: '完成', itemStyle: { color: innerRingColor, opacity: 1 }},
              { value: 100 - value, name: '未完成', itemStyle: { color: '#aac9e9' }}
            ].sort((a, b) => b.value - a.value), // 数组从大到小排序

            emphasis: {
              scale: false

            }
          },
          // colors[0]line
          {
            name: 'ring5',
            type: 'custom',
            coordinateSystem: 'none',
            renderItem: function(params, api) {
              return {
                type: 'arc',
                shape: {
                  cx: api.getWidth() / 2,
                  cy: api.getHeight() / 2,
                  r: (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.95,
                  startAngle: ((0 + self.angle) * Math.PI) / 180,
                  endAngle: ((90 + self.angle) * Math.PI) / 180
                },
                style: {
                  stroke: colors[0],
                  fill: 'transparent',
                  lineWidth: 1.5
                },
                silent: true
              }
            },
            data: [0]
          },
          {
            name: 'ring5', //        //colors[0]dot
            type: 'custom',
            coordinateSystem: 'none',
            renderItem: function(params, api) {
              let x0 = api.getWidth() / 2
              let y0 = api.getHeight() / 2
              let r = (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.95
              let point = self.getCirlPoint(x0, y0, r, 90 + self.angle)
              return {
                type: 'circle',
                shape: {
                  cx: point.x,
                  cy: point.y,
                  r: 4
                },
                style: {
                  stroke: colors[0],
                  fill: colors[0]
                },
                silent: true
              }
            },
            data: [0]
          },
          // 蓝色

          {
            name: 'ring5',
            type: 'custom',
            coordinateSystem: 'none',
            renderItem: function(params, api) {
              return {
                type: 'arc',
                shape: {
                  cx: api.getWidth() / 2,
                  cy: api.getHeight() / 2,
                  r: (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.95,
                  startAngle: ((180 + self.angle) * Math.PI) / 180,
                  endAngle: ((270 + self.angle) * Math.PI) / 180
                },
                style: {
                  stroke: colors[1],
                  fill: 'transparent',
                  lineWidth: 1.5
                },
                silent: true
              }
            },
            data: [0]
          },
          {
            name: 'ring5', // 蓝色
            type: 'custom',
            coordinateSystem: 'none',
            renderItem: function(params, api) {
              let x0 = api.getWidth() / 2
              let y0 = api.getHeight() / 2
              let r = (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.95
              let point = self.getCirlPoint(x0, y0, r, 180 + self.angle)
              return {
                type: 'circle',
                shape: {
                  cx: point.x,
                  cy: point.y,
                  r: 4
                },
                style: {
                  stroke: colors[1], // 绿
                  fill: colors[1]
                },
                silent: true
              }
            },
            data: [0]
          },

          {
            name: 'ring5',
            type: 'custom',
            coordinateSystem: 'none',
            renderItem: function(params, api) {
              return {
                type: 'arc',
                shape: {
                  cx: api.getWidth() / 2,
                  cy: api.getHeight() / 2,
                  r: (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.85,
                  startAngle: ((270 + (-self.angle)) * Math.PI) / 180,
                  endAngle: ((40 + (-self.angle)) * Math.PI) / 180
                },
                style: {
                  stroke: colors[2],
                  fill: 'transparent',
                  lineWidth: 1.5
                },
                silent: true
              }
            },
            data: [0]
          },
          // 橘色

          {
            name: 'ring5',
            type: 'custom',
            coordinateSystem: 'none',
            renderItem: function(params, api) {
              return {
                type: 'arc',
                shape: {
                  cx: api.getWidth() / 2,
                  cy: api.getHeight() / 2,
                  r: (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.85,
                  startAngle: ((90 + (-self.angle)) * Math.PI) / 180,
                  endAngle: ((220 + (-self.angle)) * Math.PI) / 180
                },
                style: {
                  stroke: colors[2],
                  fill: 'transparent',
                  lineWidth: 1.5
                },
                silent: true
              }
            },
            data: [0]
          },
          {
            name: 'ring5',
            type: 'custom',
            coordinateSystem: 'none',
            renderItem: function(params, api) {
              let x0 = api.getWidth() / 2
              let y0 = api.getHeight() / 2
              let r = (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.85
              let point = self.getCirlPoint(x0, y0, r, 90 + (-self.angle))
              return {
                type: 'circle',
                shape: {
                  cx: point.x,
                  cy: point.y,
                  r: 4
                },
                style: {
                  stroke: colors[3], // 粉
                  fill: colors[3]
                },
                silent: true
              }
            },
            data: [0]
          },
          {
            name: 'ring5', // 绿点
            type: 'custom',
            coordinateSystem: 'none',
            renderItem: function(params, api) {
              let x0 = api.getWidth() / 2
              let y0 = api.getHeight() / 2
              let r = (Math.min(api.getWidth(), api.getHeight()) / 2) * 0.85
              let point = self.getCirlPoint(x0, y0, r, 270 + (-self.angle))
              return {
                type: 'circle',
                shape: {
                  cx: point.x,
                  cy: point.y,
                  r: 4
                },
                style: {
                  stroke: colors[3], // 绿
                  fill: colors[3]
                },
                silent: true
              }
            },
            data: [0]
          }
        ]
      }
      this.drawEcharts('storageChart', this.option)
      // this.draw()
      let timer = setTimeout(() => {
        if (this.timerId) {
          clearInterval(this.timerId)
        }
        this.timerId = setInterval(() => {
          // 用setInterval做动画感觉有问题
          this.draw()
          // console.log('one setInterval2 timer execute')
        }, 100)
        clearTimeout(timer)
      }, 1000)
      // this.drawEcharts('chart', option)
    },
    getCirlPoint(x0, y0, r, angle) {
      let x1 = x0 + r * Math.cos((angle * Math.PI) / 180)
      let y1 = y0 + r * Math.sin((angle * Math.PI) / 180)
      return {
        x: x1,
        y: y1
      }
    },
    draw() {
      this.angle = this.angle + 3
	  if(!myChart){
		  return
	  }
      myChart.setOption(this.option, true)
      // this.drawEcharts('storageChart', this.option)
      // window.requestAnimationFrame(draw);
    },
    // Echarts绘图
    drawEcharts(id, option) {
      if (myChart != null && myChart != '' && myChart != undefined) {
        myChart.dispose()// 销毁
      }
      myChart = echarts.init(document.getElementById(id)) // echartsExample是显示echart的元素id
      myChart.setOption(option)

      // this.loading = false
      return myChart
    },
    drawChart2() {
      // var data = [50, 60, 70]
      // var className = ['生产进度', '补货进度', '出库进度']
      // var colorList = ['#39B3FF', '#47E0E0', '#7891D9', '#83D978', '#C7A530', '#FF8439']
      let data = [{
        name: '拣货进度',
        value: (this.chartData.pickingProgress * 100).toFixed(2)
      },
      {
        name: '补货进度',
        value: (this.chartData.replenishmentProgress * 100).toFixed(2)
      },
      {
        name: '复核进度',
        value: (this.chartData.reviewProgress * 100).toFixed(2)
      },
      {
        name: '排车进度',
        value: (this.chartData.schedulingProgress * 100).toFixed(2)
      },
      {
        name: '送货进度',
        value: (this.chartData.deliveryProgress * 100).toFixed(2)
      }
      ]
      data = data.sort((a, b) => b.value - a.value)
      let max = Math.max(...data.map(item => item.value))
      let len = Math.ceil(data.length)
      let otherLen = data.length
      let data1 = data.slice(0, len)
      let data2 = data.slice(len)
      let option = {
        // backgroundColor: 'rgba(0,0,0,.5)',
        color: '#409EFF',
        legend: {
          right: 10
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: [{
          x: '5%',
          y: '5%',
          width: '90%',
          height: '100%'
          // containLabel: true
        }, {
          x2: '5%',
          y: '5%',
          width: '90%',
          height: otherLen / len * 100 + '%'
          // containLabel: true
        }],
        yAxis: [{
          type: 'category',
          gridIndex: 0,
          axisLine: {
            show: 0
          },
          axisLabel: {
            verticalAlign: 'bottom',
            align: 'left',
            padding: [0, 0, 5, 10],
            color: '#fff',
            fontSize: '12',
            formatter: (p, index) => {
              return '{index|' + (index + 1) + '} ' + p
            },
            rich: {
              index: {
                color: '#26BCFF',
                fontSize: '18',
                fontWeight: 'bold'
              }
            }
          },
          axisTick: {
            show: 0
          },
          inverse: true,
          data: data1.map(item => item.name)
        }, {
          type: 'category',
          gridIndex: 0,
          axisLine: {
            show: 0
          },
          axisLabel: {
            verticalAlign: 'bottom',
            align: 'right',
            padding: [0, 0, 5, 10],
            textStyle: {
              color: '#fff',
              fontSize: '12'
            },
            formatter: params => {
              return '{num|' + params + '}%'
            },
            rich: {
              num: {
                color: '#FF982E',
                fontSize: '18',
                fontWeight: 'bold'
              }
            }
          },
          axisTick: {
            show: 0
          },
          inverse: true,
          data: data1.map(item => item.value)
        }, {
          type: 'category',
          gridIndex: 1,
          axisLine: {
            show: 0
          },
          axisLabel: {
            verticalAlign: 'bottom',
            align: 'left',
            padding: [0, 0, 15, 10],
            color: '#fff',
            fontSize: '16',
            formatter: (p, index) => {
              return '{index|' + (index + len + 1) + '} ' + p
            },
            rich: {
              index: {
                color: '#26BCFF',
                fontSize: '26',
                fontWeight: 'bold'
              }
            }
          },
          axisTick: {
            show: 0
          },
          inverse: true,
          data: data2.map(item => item.name)
        }, {
          type: 'category',
          gridIndex: 1,
          axisLine: {
            show: 0
          },
          axisLabel: {
            verticalAlign: 'bottom',
            align: 'right',
            padding: [0, 0, 15, 10],
            textStyle: {
              color: '#fff',
              fontSize: '26'
            },
            formatter: params => {
              return '{num|' + params + '}%'
            },
            rich: {
              num: {
                color: '#FF982E',
                fontSize: '26',
                fontWeight: 'bold'
              }
            }
          },
          axisTick: {
            show: 0
          },
          inverse: true,
          data: data2.map(item => item.value)
        }],
        xAxis: [{
          show: 0,
          type: 'value',
          gridIndex: 0,
          max: max,
          axisLine: {
            show: 0
          },
          axisTick: {
            show: 0
          },
          splitLine: {
            show: 0
          }
        }, {
          show: 0,
          gridIndex: 1,
          max: max,
          type: 'value',
          axisLine: {
            show: 0
          },
          axisTick: {
            show: 0
          },
          splitLine: {
            show: 0
          }
        }],
        series: [{
          type: 'bar',
          barWidth: 10,
          xAxisIndex: 0,
          yAxisIndex: [0, 1],
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
              offset: 0,
              color: '#72AEFF' // 0% 处的颜色
            }, {
              offset: 1,
              color: '#0084FF' // 100% 处的颜色
            }], false),
            barBorderRadius: 5
          },
          showBackground: true,
          backgroundStyle: {
            color: '#263877',
            barBorderRadius: 5
          },
          data: data1
        }, {
          type: 'bar',
          barWidth: 10,
          xAxisIndex: 1,
          yAxisIndex: [2, 3],
          itemStyle: {
            barBorderRadius: 5
          },
          showBackground: true,
          backgroundStyle: {
            color: '#263877',
            barBorderRadius: 5
          },
          data: data2
        }]
      }
      this.drawEcharts2('progressChart', option)
    },

    // Echarts绘图
    drawEcharts2(id, option) {
      if (progressChart != null && progressChart != '' && progressChart != undefined) {
        progressChart.dispose() // 销毁
      }
      progressChart = echarts.init(document.getElementById(id)) // echartsExample是显示echart的元素id
      progressChart.setOption(option)
      // this.loading = false
      return progressChart
    }
  }
}
</script>

<style lang="scss" scoped>
.one {
  position: relative;
  width: 649px;
  height: 275px;
  background-image: url('~@/assets/img/home-page/one.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  .main {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .chart {
    width: 50%;
    height: 220px;
  }
  .charts {
    width: 50%;
    height: 200px;
  }
}
</style>
